package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.service.entrustpay.EntrustPayService;

/** 
 * @ClassName: EntrustPayJob 
 * @Description: 委托代收 交易 清理超时订单
 * <per>
 *   查询 cps主订单 内部交易码 00666 状态 30101 超过12小时
 * </per>
 * @author  lx
 * @date 2016年12月31日 下午8:35:21  
 */

public class EntrustPayTimeoutJob extends GopayBaseJob {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Resource(name = "entrustPayService")
    EntrustPayService entrustPayService;
    
    @Resource(name = "cpsGeneralMainOrderOperClient")
    MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;
    /* 委托代收 交易超时执行任务
     *  
     *   
     * @see com.gopay.scheduler.GopayBaseJob#doJobInternal() 
     */
    @Override
    protected void doJobInternal() {
            logger.error("=================委托代收交易清理超时任务===start==============");
            List<CpsGenMainOrder> list =  entrustPayService.getEntrustPayTimeoutOrderList();
            updateOrderStatus(list);
            logger.error("=================委托代收交易清理超时任务====end=============");
    }
    
	private void updateOrderStatus(List<CpsGenMainOrder> list) {
		if (!list.isEmpty()) {
			String txnStaCode = String.valueOf(TxnStaCode.TXN_STA_CD_20001.value);
			logger.info("找到" + list.size() + "条委托代收超时订单, 开始执行清理任务!");

			Map<MainOrderField, String> map = new HashMap<MainOrderField, String>();

			map.put(MainOrderField.TXN_STA_CD, txnStaCode);
			Date date = new Date();
			SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
			map.put(MainOrderField.TRAN_FINISH_TIME, sf.format(date));
			map.put(MainOrderField.LAST_UPD_TS, sf.format(date));
			map.put(MainOrderField.ERR_MSG,"超过12小时状态仍为30101");
			map.put(MainOrderField.ERR_CODE, "100E5042");
			for (CpsGenMainOrder order : list) {
				String gopayOrderId = order.getGopayOrderId();
				logger.info("委托代收，处理银行返回超时订单，orderId:" + gopayOrderId);
				try {
					cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, map);
				} catch (GopayException e) {
					logger.error("update order fail,orderId:" + gopayOrderId.toString(), e);
				} catch (Exception e) {
					logger.error("update order fail,orderId:" + gopayOrderId, e);
				}

			}
		}
	}
}
